<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="form.userName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">角色信息</h4>
    <el-table v-loading="loading" :row-key="getRowKey" @row-click="clickRow" ref="tableRef" @selection-change="handleSelectionChange" :data="roles.slice((pageNum-1)*pageSize,pageNum*pageSize)">
      <el-table-column label="序号" type="index" align="center">
        <template #default="scope">
          <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
      <el-table-column label="角色编号" align="center" prop="roleId" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="权限字符" align="center" prop="roleKey" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="pageNum" v-model:limit="pageSize" />

    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getAuthRole, updateAuthRole } from "@/api/system/user";
import { ElForm, ElTable, ElMessage } from 'element-plus'
import { parseTime } from '@/utils/cj'

interface Role {
  roleId: number;
  roleName: string;
  roleKey: string;
  flag?: boolean;
  createTime: string;
}

interface User {
  userId: number;
  userName: string;
  nickName: string;
}

defineOptions({
  name: "AuthRole"
})

const router = useRouter();

const formRef = ref<InstanceType<typeof ElForm>>()
const tableRef = ref<InstanceType<typeof ElTable>>()

// 遮罩层
const loading = ref(true)
// 分页信息
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 选中角色编号
const roleIds = ref<number[]>([])
// 角色信息
const roles = ref<Role[]>([])
// 用户信息
const form = ref<User>({} as User)

onMounted(() => {
  const userId = router.currentRoute.value.params?.userId;
  if (userId) {
    loading.value = true;
    getAuthRole(userId as string).then((response: any) => {
      form.value = response.user;
      roles.value = response.roles;
      total.value = roles.value.length;
      nextTick(() => {
        roles.value.forEach((row) => {
          if (row.flag) {
            tableRef.value?.toggleRowSelection(row);
          }
        });
      });
      loading.value = false;
    });
  }
})

/** 单击选中行数据 */
const clickRow = (row: Role) => {
  tableRef.value?.toggleRowSelection(row);
}

// 多选框选中数据
const handleSelectionChange = (selection: Role[]) => {
  roleIds.value = selection.map(item => item.roleId);
}

// 保存选中的数据编号
const getRowKey = (row: Role) => {
  return row.roleId;
}

/** 提交按钮 */
const submitForm = () => {
  const userId = form.value.userId;
  const roleIdsStr = roleIds.value.join(",");
  updateAuthRole({ userId: userId, roleIds: roleIdsStr }).then((response: any) => {
    ElMessage.success("授权成功");
    close();
  });
}

/** 关闭按钮 */
const close = () => {
  // 由于 $tab 是自定义属性，无法通过类型推断，暂时使用 any
  const tab: any = (window as any).$tab || proxy?.$tab;
  if (tab) {
    tab.closeOpenPage({ path: "/system/user" });
  }
}
</script>
